package aa.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.rowset.RowSetProvider;
import javax.sql.rowset.WebRowSet;

public class DBTools {
//建立与数据库连接
	public static Connection getConn() {
		Connection connection = null;
	
		try {
			Class.forName("org.mariadb.jdbc.Driver");
		 connection=DriverManager.getConnection("jdbc:mariadb://10.220.140.102:3366/studb11","stua","zHZUA65r");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return connection;
	}


    public static int doSql(String sql) {
    	int ret = 0;
    	Connection conn = getConn();
    	
    	
    	try {
    		Statement stmt = conn.createStatement();
    		System.out.println("sql=" + sql);
    		ret = stmt.executeUpdate(sql);
    		stmt.close();
        	conn.close();
    	}catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return ret;
	}
   	

    	 
  public static ResultSet query(String sql) {
	  Connection conn = getConn();
	  ResultSet rs = null;
  	try {
  		Statement stmt=conn.createStatement();
  		System.out.println("DBTools query() sql=" + sql);
  		rs = stmt.executeQuery(sql);
  		stmt.close();
      	conn.close();
  	}catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return rs; 
	 
  }
  
  public static WebRowSet getRS(String sql) {
	  Connection conn = getConn();
	  WebRowSet wrs = null;
  	try {
  		Statement stmt=conn.createStatement();
  		System.out.println("DBTools query() sql=" + sql);
  		ResultSet rs = stmt.executeQuery(sql);
  		wrs = RowSetProvider.newFactory().createWebRowSet();
  		//rs--->wrs
  		
  		wrs.populate(rs);
  		
  		
  		
  		rs.close();
  		stmt.close();
      	conn.close();
  	} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return wrs; 
  }
  
  }





